<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">后台管理系统</h2>
      <el-form ref="formRef" :rules="rules" :model="form" class="login-form">
        <el-form-item label-width="70px" label-position="right" label="用户名:" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label-width="70px" label-position="right" label="密码:" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-button type="primary" class="login-button" @click="handleLogin">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { LoginForm } from "../../apis";
import useUserStore from "../../store/modules/user";
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";

const userStore = useUserStore()
const form = reactive<LoginForm>({
  username: "admin",
  password: "123456",
});

const formRef = ref<FormInstance>()
const router = useRouter()
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' }
  ]
})

const handleLogin = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await userStore.login(form)
        ElMessage({
          message: "登录成功",
          type: "success",
        });
        router.push("/")
      } catch (error) {
        ElMessage({
          message: "登录失败",
          type: "error",
        });
      }
    }
  })
}
</script>

<style scoped lang="scss">
.login-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 30px;
}

.login-form {
  :deep(.el-form-item__label) {
    font-size: 14px;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none;
    border: 1px solid #dcdfe6;
  }
}

.login-button {
  width: 100%;
  margin-top: 20px;
  height: 40px;
  background-color: #409eff;
}
</style>